package backtracking.leetcode.medium;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author bruin_du
 * @description 含有重复元素集合的组合
 * @date 2022/9/6 0:05
 **/
public class OfferII082_CombinationSum2 {
    List<List<Integer>> lists = new ArrayList<>();
    List<Integer> list = new ArrayList<>();
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        dfs(candidates, target, 0);
        return lists;
    }

    private void dfs(int[] candidates, int target, int index) {
        if (target == 0) {
            lists.add(new ArrayList<>(list));
            return;
        }
        for (int i = index; i < candidates.length; i++) {
            if (candidates[i] > target) break;// 剪枝，后面的元素已经大于所需的值了
            if (i > index && candidates[i] == candidates[i - 1]) {
                // 剪枝、避免重复
                // 因为前面那个同样的数已经经历过dfs，再拿同样的数dfs就会得到重复的答案
                // 并且只要相同元素下标最小的那个，否则会漏掉可能的结果
                continue;
            }
            list.add(candidates[i]);
            dfs(candidates, target - candidates[i], i + 1);
            list.remove(list.size() - 1);
        }
    }
}
